package com.cloud.logger.zchain.zchainserver.mail.impl;

import com.cloud.logger.zchain.core.common.base.ResultMessage;
import com.cloud.logger.zchain.core.common.constant.ResultCodeConstant;
import com.cloud.logger.zchain.core.exception.BusinessException;
import com.cloud.logger.zchain.zchainserver.base.PagePo;
import com.cloud.logger.zchain.zchainserver.entity.AngelaLoggerProjectNode;
import com.cloud.logger.zchain.zchainserver.entity.MailFailure;
import com.cloud.logger.zchain.zchainserver.entity.MailSuccess;
import com.cloud.logger.zchain.zchainserver.mail.MailInfo;
import com.cloud.logger.zchain.zchainserver.mail.MailService;
import com.cloud.logger.zchain.zchainserver.mail.util.MailSendUtil;
import com.cloud.logger.zchain.zchainserver.mongo.MailFailureRepository;
import com.cloud.logger.zchain.zchainserver.mongo.MailInfoRepository;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 浙江卓锐科技股份有限公司
 *
 * @author zhengyt
 * @create 2017/11/10
 * @description
 */
@Service
public class MailServiceImpl implements MailService {

    @Resource
    MailInfoRepository mailMapper;
    @Resource
    MailFailureRepository mailFailureMapper;
    @Resource
    private MongoTemplate mongoTemplate;

    static String SUCCESS = "success";
    static String FAILURE = "failure";

    @Override
    public ResultMessage<MailSuccess> save(MailSuccess mailSuccess) {
        ResultMessage resultMessage = new ResultMessage();
        if (Strings.isBlank(mailSuccess.getAddress())) {
            resultMessage.setMessage("邮箱地址不能为空！");
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
            return resultMessage;
        }
        mailSuccess = mailMapper.save(mailSuccess);
        if (mailSuccess.getId() != null) {
            resultMessage.setCode(ResultCodeConstant.SERVICE_SUCCESS_CODE);
            resultMessage.setId(mailSuccess.getId() + "");
        } else {
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
        }
        return resultMessage;
    }

    @Override
    public ResultMessage sendMail(MailSuccess mailSuccess) {
        ResultMessage resultMessage = new ResultMessage();
        boolean flag = SendMail(mailSuccess.getAddress(), mailSuccess.getContent(), mailSuccess.getContent());
        if(!flag){
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
            return resultMessage;
        }
        resultMessage.setCode(ResultCodeConstant.SERVICE_SUCCESS_CODE);
        return resultMessage;
    }

    public ResultMessage sendHtmlMail(MailInfo mailInfo, AngelaLoggerProjectNode node) {
        ResultMessage resultMessage = new ResultMessage();

        MailSuccess mailSuccess = new MailSuccess();
        mailSuccess.setAddress(mailInfo.getToAddress());
        mailSuccess.setContent(mailInfo.getContent());
        mailSuccess.setCreateTime(new Date());
        mailSuccess.setCode(node.getCode());
        mailSuccess.setIp(node.getIp());
        mailSuccess.setPort(node.getPort());
        try {
            MailSendUtil.sendHtmlMail(mailInfo);
            resultMessage.setCode(ResultCodeConstant.SERVICE_SUCCESS_CODE);
            //存到发送失败的表
            mailMapper.insert(mailSuccess);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
            resultMessage.setMessage("发送邮件失败");
            MailFailure mailFailure = new MailFailure();
            mailFailure.mailFailure(mailSuccess);
            //存到发送失败的表
            mailFailureMapper.insert(mailFailure);
        }
        return resultMessage;
    }

    @Override
    public ResultMessage<MailSuccess> getMail(String id,String type) {
        ResultMessage resultMessage = new ResultMessage();
        try {
            if(SUCCESS.equals(type)){
                MailSuccess mailSuccess = (MailSuccess) mailMapper.findOne(id);
                resultMessage.setContent(mailSuccess);
            }else if(FAILURE.equals(type)){
                MailFailure mailFailure = (MailFailure) mailFailureMapper.findOne(id);
                resultMessage.setContent(mailFailure);
            }

        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
            resultMessage.setMessage("查询失败");
        }
        return resultMessage;
    }

    @Override
    public ResultMessage<MailSuccess> update(MailSuccess mailSuccess) {
        ResultMessage resultMessage = new ResultMessage();
        try {
            mailMapper.save(mailSuccess);
            resultMessage.setCode(ResultCodeConstant.SERVICE_SUCCESS_CODE);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
            resultMessage.setMessage("更新失败");
        }
        return resultMessage;
    }

    @Override
    public ResultMessage select(MailSuccess mailSuccess) {
        ResultMessage resultMessage = new ResultMessage();
        try {
            List<MailSuccess> mailSuccessList = mailMapper.findAll();
            resultMessage.setContent(mailSuccessList);
            resultMessage.setCode(ResultCodeConstant.SERVICE_SUCCESS_CODE);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
            resultMessage.setMessage("查询失败");
        }
        return resultMessage;

    }

    @Override
    public ResultMessage removeById(Long id) {
        ResultMessage resultMessage = new ResultMessage();
        try {
            mailMapper.delete(id);
        }catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
        }
        return resultMessage;
    }

    @Override
    public Page findMailSuccess(PagePo<MailSuccess> pageInfo) throws Exception{
        Criteria criteria = new Criteria();
        criteria.where("1").is("1");
        MailSuccess mailSuccess = pageInfo.getFields();

        if(StringUtils.isBlank(mailSuccess.getCode())){
            throw new BusinessException("项目code不能为空！");
        }

        if(StringUtil.isNotEmpty(mailSuccess.getCode())){
            criteria.and("code").regex(mailSuccess.getCode());
        }

        // 查询出一共的条数
        Long count = mongoTemplate.count(new Query(criteria), MailSuccess.class);

        Pageable pageable = new PageRequest(pageInfo.getPageNo(), pageInfo.getPageSize());

        List<MailSuccess> list = mongoTemplate.find(new Query(criteria).with(new Sort(Sort.Direction.DESC, "createTime")).with(pageable),MailSuccess.class);

        Page<MailSuccess> pagelist = new PageImpl<MailSuccess>(list, pageable, count);
        return pagelist;
    }

    @Override
    public Page findMailFailure(PagePo<MailFailure> pageInfo) throws Exception{
        Criteria criteria = new Criteria();
        criteria.where("1").is("1");
        MailFailure mailFailure = pageInfo.getFields();

        if(StringUtils.isBlank(mailFailure.getCode())){
            throw new BusinessException("项目code不能为空！");
        }

        if(StringUtil.isNotEmpty(mailFailure.getCode())){
            criteria.and("code").regex(mailFailure.getCode());
        }

        // 查询出一共的条数
        Long count = mongoTemplate.count(new Query(criteria), MailFailure.class);

        Pageable pageable = new PageRequest(pageInfo.getPageNo(), pageInfo.getPageSize());

        List<MailFailure> list = mongoTemplate.find(new Query(criteria).with(new Sort(Sort.Direction.DESC, "createTime")).with(pageable),MailFailure.class);

        Page<MailFailure> pagelist = new PageImpl<MailFailure>(list, pageable, count);
        return pagelist;
    }

    boolean SendMail(String address, String title, String content) {
        try {
            MailSendUtil.sendMail(address, title, content);
            System.out.println(" 邮件发送成功.. ");
//            mailMapper.deleteByPrimaryKey(id);
            return true;
        } catch (Exception e) {
            System.out.println(" 发送失败 ");
            System.out.println(e.getLocalizedMessage());
            MailFailure mailFailure = new MailFailure();
            mailFailure.setAddress(address);
            mailFailure.setContent(content);
            //存到发送失败的表
            mailFailureMapper.insert(mailFailure);
            return false;
        }
    }
}